package j29;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author chengshuai
 * @date 2021/4/13 9:55
 * <p>
 * 自旋锁，实现
 */
public class SpinLockDemo {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock() {
        Thread thread = Thread.currentThread();
        boolean b = true;

        //A替换成功，B一直自旋
        //B解锁后，B替换成功，不再自旋而已
        while (!atomicReference.compareAndSet(null, thread)) {
            if (b) {
                System.out.println(Thread.currentThread().getName() + "\t lock");
                b = false;
            }
        }
    }

    public void myUnlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread, null);
        System.out.println(Thread.currentThread().getName() + "\t unlock");
    }

    public static void main(String[] args) {

        SpinLockDemo spinLockDemo = new SpinLockDemo();

        new Thread(() -> {
            spinLockDemo.myLock();
            ThreadUtil.sleep(5000);
            spinLockDemo.myUnlock();
        }, "AA").start();

        ThreadUtil.sleep(1000);

        new Thread(() -> {
            spinLockDemo.myLock();
            spinLockDemo.myUnlock();
        }, "BB").start();
    }

}
